#include "../include/filehandle.h"
#pragma warning(disable : 4996)

extern MemoryNode<dword> CodeMem[65536];
extern MemoryNode<byte> DataMem[65536];

extern bool RUNNING, ERROR, Zero, Sign;

extern word CodeH, CodeL;
extern IREG intRegs[128];
extern FREG floatReg[64];
extern DREG doublReg[64];

#if !defined(__debug__)
static void init(bool is_code, word target, word size)
{
    if (is_code)
    {
        CodeMem[target].data = new dword[size];
        CodeMem[target].size = size;
    }
    else
    {
        DataMem[target].data = new byte[size];
        DataMem[target].size = size;
    }
}
#endif

fHeader getHeader(const char *filename)
{
    FILE *fp = fopen(filename, "rb");
    if (fp == NULL)
    {
        printf("fatal error:file not found.\n");
        exit(1);
    }
    fHeader header;
    fread(&header, sizeof(fHeader), 1, fp);
    fclose(fp);
    if (strcmp(header.magic, "sandbox\x00") != 0)
    {
        printf("fatal error:file type error.\n");
        exit(1);
    }
    else if (header.version != 0x0205)
    {
        printf("fatal error:file version error.\n");
        exit(1);
    }
    return header;
}
void loadImage(const char *filename, fHeader fMessage)
{
    FILE *fp = fopen(filename, "rb");
    if (fp == NULL)
    {
        printf("fatal error:file not found.\n");
        exit(1);
    }
    pHeader pMessage;
    fseek(fp, 0x10, SEEK_SET);
    fread(&pMessage, sizeof(pHeader), 1, fp);
    fseek(fp, pMessage.fBegin, 0);
    init(true, pMessage.pEntry >> 16, pMessage.pSize);
    fread(CodeMem[pMessage.pEntry >> 16].data + (pMessage.pEntry & 0xffff), sizeof(dword), pMessage.pSize, fp);
    fseek(fp, 0x18, SEEK_SET);
    fread(&pMessage, sizeof(pHeader), 1, fp);
    fseek(fp, pMessage.fBegin, 0);
    init(false, pMessage.pEntry >> 16, pMessage.pSize);
    fread(DataMem[pMessage.pEntry >> 16].data + (pMessage.pEntry & 0xffff), sizeof(byte), pMessage.pSize, fp);
    fclose(fp);
}